package com.xuzimian.globaldemo.spring.security.oauth2.server.config;

import com.xuzimian.globaldemo.spring.security.oauth2.server.service.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 开启 并配置Spring  Security 登录，校验权限，授权等机制
 *
 * @program: global-demo
 * @description:
 * @author: xzm
 * @create: 2019-06-21 17:03
 **/
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    // @Autowired
    // private ClientRegistrationRepository clientRegistrationRepository;


    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder()); //自定义用户
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("user").password(passwordEncoder.encode("user")).roles("USER");
        auth.eraseCredentials(false);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定义登陆应用
        http.formLogin().loginPage("/login").permitAll().successHandler(new LoginSuccessHandler())
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/deny").permitAll()
                .and().authorizeRequests()
                .antMatchers("/images/**", "/checkcode", "/scripts/**", "/styles/**").permitAll()
                // 注释该行避免覆盖注解 @PreAuthorize("authenticated")的拦截
                //  .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and().exceptionHandling().accessDeniedPage("/deny")
                .and().rememberMe().tokenValiditySeconds(86400)
                .and().csrf().disable();
        //.tokenRepository(new InMemoryTokenRepositoryImpl());
        // .tokenRepository(tokenRepository());
    }
}
